package com.dingding.common.core.base.dto;

import java.lang.reflect.ParameterizedType;

import org.apache.http.HttpStatus;

import com.dingding.common.core.base.code.BaseCodeMessage;
import com.dingding.common.core.util.JSONUtil;
import com.dingding.common.core.util.paravalidate.ValiResult;
import com.dingding.common.core.util.paravalidate.ValidateUtil;

/**
 * 
 * @ClassName: AbstractResponse
 * @Description: 客户客户端请求数据
 * @author CHEHAUNBO
 * @date 2016年6月5日 下午11:03:20
 * @param <T>
 * 
 */
@SuppressWarnings("all")
public abstract class AbstractResponse<T, M> {

	protected Class<T> clazzT = null;
	protected Class<M> clazzM = null;

	public AbstractResponse() {
		if (this.clazzT == null) {
			this.clazzT = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass())
					.getActualTypeArguments()[0];
		}
		if (this.clazzM == null) {
			this.clazzM = (Class<M>) ((ParameterizedType) getClass().getGenericSuperclass())
					.getActualTypeArguments()[1];
		}
	}

	/**
	 * 
	 * @Title: parseRequestJson
	 * @param requestJson
	 *            客户端请求的JSON数据
	 * @return T JSON转换后的业务BEAN
	 * @author CHEHAUNBO
	 * 
	 */
	public <M> M parseRequestJson(String requestJson) {

		return (M) JSONUtil.getRequestBody(requestJson, clazzM);
	}

	/**
	 * 
	 * @Title: parseRequestJson
	 * @param requestJson
	 *            客户端请求的JSON数据
	 * @return T JSON转换后的业务BEAN
	 * @author CHEHAUNBO
	 * 
	 */
	public <T> T parseRequestJson(String requestJson, Class<T> cls) {

		return (T) JSONUtil.getRequestBody(requestJson, cls);
	}

	/**
	 * 将响应数据转换成JSON
	 * 
	 * @Title: responseBeanToJson
	 * @return String 将响应数据转换成JSON后的数据
	 * @author CHEHAUNBO
	 * 
	 */
	public <T> String responseBeanToJson(ResponseEntity<T> responseEntity) {
		return JSONUtil.toJSONString(responseEntity, "yyyy-MM-dd HH:mm:ss");
	}

	/**
	 * @Description:将responsebean转化成字符串，并且把时间格式化成指定格式
	 * @author fengshuonan
	 * @since 2.3.2
	 */
	public <T> String responseBeanToJson(ResponseEntity<T> responseEntity, String dateFormatPattern) {
		return JSONUtil.toJSONString(responseEntity, dateFormatPattern);
	}

	/**
	 * 验证客户端请求参数是否合法
	 * 
	 * @Title: validateParam
	 * @author CHEHAUNBO
	 * @since V2.2.0
	 * 
	 */
	protected <T, M> boolean validateParam(ResponseEntity<T> response, M reqCalculateDistance) {

		ValiResult valiResult = ValidateUtil.validateBeanIsAvaliable(reqCalculateDistance,
				reqCalculateDistance.getClass());

		if (!valiResult.isAvailable()) {// 参数为空
			response.setCode(HttpStatus.SC_FORBIDDEN);
			response.setNullPropList(valiResult.getNullFieldList()); // 空字段名称
			response.setErrorMessage(BaseCodeMessage.DATA_NULL_PARAM_MESSAGE);
			response.setPromptMessage(BaseCodeMessage.HTTP_REQUEST_ERROR);
			return false;
		}
		return true;

	}

}
